package com.seeyon.apps.zhiwei.nbtest.eventlisteners;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.zhiwei.nbtest.PluginInit;
import com.seeyon.apps.zhiwei.nbtest.util.FormUtil;
import com.seeyon.apps.zhiwei.nbtest.util.RestUtil;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormDataSubBean;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataDAO;
import com.seeyon.cap4.form.modules.engin.base.formData.CAP4FormDataManager;
import com.seeyon.cap4.form.service.CAP4FormCacheManager;
import com.seeyon.cap4.form.service.CAP4FormManager;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.workflow.event.AbstractWorkflowEvent;
import com.seeyon.ctp.workflow.event.WorkflowEventData;
import com.seeyon.ctp.workflow.event.WorkflowEventResult;
import com.seeyon.ctp.workflow.util.WorkflowEventConstants;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import org.apache.http.HttpEntity;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;

import org.apache.http.entity.StringEntity;

import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.math.BigDecimal;

import java.net.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
//日志注释
@Getter
//getset注释
@Setter
public class NbtestEvent extends AbstractWorkflowEvent {
//    声明了一个处理前事件监听类继承了工作流事件的抽象类

    public static String form = "formmain_0000";
//    声明了一个静态的 form属性并赋值

    private CAP4FormManager cap4FormManager;//表单管理
    private CAP4FormCacheManager cap4FormCacheManager;//缓存管理
    private CAP4FormDataManager cap4FormDataManager;//数据管理
    private CAP4FormDataDAO cap4FormDataDAO;//数据操作类
    private ColManager colManager;

    public WorkflowEventConstants.WorkflowEventType getType() {

        return super.getType();
    }

    public ApplicationCategoryEnum getAppName() {
        return ApplicationCategoryEnum.form;
    }

    @Override
    public String getId() {// 这个是唯一ID

        return "nbtestEvent";
    }

    @Override
    public String getLabel() {//这个是在开发高级里面显示的事件名称

        return "nbtest处理前事件";
    }

    //注意所有的中断操作，都只能在“前事件”通过设置setAlertMessage来完成，
    // 比如想在发起做中断判断，只能在发起前事件，而不能再发起事件中设置，否则中断无效
    // 流程事件：发起前事件
    public WorkflowEventResult onBeforeStart(WorkflowEventData data) {
        log.info(getLabel()+"发起前时间");
        return  null;
    }



    //节点操作事件：处理前事件
    public WorkflowEventResult onBeforeFinishWorkitem(WorkflowEventData data) {
        log.info(getLabel() + " 处理前事件");
        WorkflowEventResult result = new WorkflowEventResult();
        try {
            Map<String, Object> map = data.getBusinessData();
//                public Map<String, Object> getBusinessData() {
//                return this.businessData;
//          }
//            FormDataMasterBean masterBean = (FormDataMasterBean) map.get("formDataBean");
////            从map里面get的数据强制转换为 FormDataMasterBean类型
//            String birthday = FormUtil.getFieldValue(masterBean, "birthday")+"";
//            //审批的时候一定要是 “浏览”才能回写进去
//            FormUtil.setCellValue(masterBean, "age", "10086");
//
//            Map<String, List<FormDataSubBean>> subDataMap = FormUtil.getSubDataMap(masterBean);
//            List<FormDataSubBean> list = subDataMap.get("家庭表");
//            for (FormDataSubBean formDataSubBean : list){
//                FormUtil.setCellValue(formDataSubBean, "xm", "caonima");
//            }
//
//                result.setAlertMessage("222222");


//            处理前事件一

//            实例化对象masterBean 获取到当前传入的form表单的所有bean
            FormDataMasterBean masterBean = (FormDataMasterBean)map.get("formDataBean");

//            获取到主表的某个控件的值
            String score = FormUtil.getFieldStrValue(masterBean,"score")+"";
//            设置score字段的默认值
//            FormUtil.setCellValue(masterBean,"score","nbtext");

//            首先用map获取到的form表单的所有明细表list
            Map<String, List<FormDataSubBean>> subDataMap = FormUtil.getSubDataMap(masterBean);
//            用get方法获取到语文考试的明细表
            List<FormDataSubBean>listC = subDataMap.get("语文考试");
            double sumC = 0;
//            遍历语文考试表获取某个控件的值进行操作
            for (FormDataSubBean formDataSubBean : listC){
                FormUtil.setCellValue(formDataSubBean, "语文考试名称", "caonima");
//                获取到控件里面的文本值强转为double型
                String scoreCs= FormUtil.getFieldStrValue(formDataSubBean,"语文分数");
                double scoreCf = Double.parseDouble(scoreCs);
                sumC += scoreCf;
            }

            List<FormDataSubBean>listM = subDataMap.get("数学考试");
            double sumM = 0;
            for (FormDataSubBean formDataSubBean : listM){
                FormUtil.setCellValue(formDataSubBean, "数学考试名称", "woaini");
                String scoreCs= FormUtil.getFieldStrValue(formDataSubBean,"数学分数");
                double scoreCf = Double.parseDouble(scoreCs);
                sumM += scoreCf;
            }

            double sum = sumC + sumM * 2;
//            四舍五入把保留一位小数 使用bigDecimal的setScale方法 保留一位 round_up向上取整的方法
            BigDecimal bigDecimal = new BigDecimal(sum);
//            FormUtil.setCellValue(masterBean,"score",bigDecimal.setScale(1,BigDecimal.ROUND_HALF_UP).doubleValue());

//


            //            处理前事件二

            //            首先获取到表单的一些属性 然后包装成json 通过http传到postman postman对属性进行修改再回写？
            String name = FormUtil.getFieldStrValue(masterBean,"姓名");
            String age = FormUtil.getFieldStrValue(masterBean,"年龄");
            String dept = FormUtil.getFieldStrValue(masterBean,"部门");
            String job = FormUtil.getFieldStrValue(masterBean,"职业");

//
//            String getMessage = interfaceUtil("http://qqlykm.cn/api/api/tq.php?city=诸暨","");
//            FormUtil.setCellValue(masterBean,"id",getMessage);
//            FormUtil.setCellValue(masterBean,"score","表示流程已经经过了get");
//            String postResult = null;
//            HttpClient client = HttpClients.createDefault();
//            URIBuilder builder = new URIBuilder();
//            URI uri = null;
//            try {
//                uri = builder.setScheme("https")
//                        .setHost("localhost:7688")
//                        .setPath("/TGCtrlApi")
//                        .build();
//
//                HttpPost post = new HttpPost(uri);
//                //设置请求头
//                post.setHeader("Content-Type", "application/json");
//                String body = "{\"serverName\":\"{0DADE507-64D6-4306-956A-2ED144FF0ED1}\",\"funcName\":\"TG_SetConfig\",\"param\":\"{\\\"config\\\":\\\"{\\\\\\\"sectionList\\\\\\\":[{\\\\\\\"TGPrintCtrl\\\\\\\":{\\\\\\\"ProjectID\\\\\\\":\\\\\\\"5000000045\\\\\\\",\\\\\\\"ProjectSecret\\\\\\\":\\\\\\\"d6fbe393a6b89ea2b70c9dce8da24088\\\\\\\"}},{\\\\\\\"GetSealList\\\\\\\":{\\\\\\\"project_id\\\\\\\":\\\\\\\"5000000045\\\\\\\",\\\\\\\"project_secret\\\\\\\":\\\\\\\"d6fbe393a6b89ea2b70c9dce8da24088\\\\\\\"}}]}\\\"}\"}";
//                //设置请求体
//                post.setEntity(new StringEntity(body));
//                //获取返回信息
//                HttpResponse response = client.execute(post);
//                postResult = response.toString();
//            } catch (Exception e) {
//                System.out.println("接口请求失败"+e.getStackTrace());
//            }
//            System.out.println(result);
//
//            FormUtil.setCellValue(masterBean,"id",postResult);
//            FormUtil.setCellValue(masterBean,"score","表示流程已经经过了get");


            String res = RestUtil.get("诸暨天气","http://qqlykm.cn/api/api/tq.php?city=诸暨");
            FormUtil.setCellValue(masterBean,"id",res);

            Map<String, Object> params = new HashMap<String,Object>();
            params.put("serverName","{0DADE507-64D6-4306-956A-2ED144FF0ED1}");
            params.put("funcName","TGGetSystemTempPath");
            params.put("param","{}");

            String postRes = RestUtil.post("传输测试", PluginInit.U8_ServerUrl,params);
//          从返回的json体里面取出某一个特定的值  对于key和value

            JSONObject.parseObject(postRes).getString("result");

            FormUtil.setCellValue(masterBean,"score",postRes);
            JSONObject postJson = JSON.parseObject(postRes);
            if (postJson.get("result").toString().equals("-1")) {
                throw new Exception(postJson.get("errorMsg").toString());
            }






//            result.setAlertMessage("222222");返回页面消息222222 可以用于判断控件的数值是否满足规定的需求



        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.setAlertMessage(e.getMessage());
        }
        return result;
    }



    //流程事件：终止前事件
    public WorkflowEventResult onBeforeStop(WorkflowEventData data) {
        log.info(getLabel() + " 发起前事件");

        return null;
    }


    //节点操作事件：回退前事件
    public WorkflowEventResult onBeforeStepBack(WorkflowEventData data) {
        log.info(getLabel() + " 回退前事件");
        return null;
    }

    //节点操作事件：取回前事件
    public WorkflowEventResult onBeforeTakeBack(WorkflowEventData data) {
        log.info(getLabel() + " 取回前事件");
        return null;
    }

    //流程事件：撤销前事件
    public WorkflowEventResult onBeforeCancel(WorkflowEventData data) {
        log.info(getLabel() + " 撤销前事件");
        return null;
    }

    public static String sendHttpPost(String url, String body) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        httpPost.addHeader("Content-Type", "application/json");
        httpPost.setEntity(new StringEntity(body));

        CloseableHttpResponse response = httpClient.execute(httpPost);
        System.out.println(response.getStatusLine().getStatusCode() + "\n");
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        System.out.println(responseContent);

        response.close();
        httpClient.close();
        return responseContent;
    }







    }




